package com.seek.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.bankfourfactor.BankCarFactorEntity;
import com.bankfourfactor.BankFourFactor;
import com.bankfourfactor.RetCodeEnum;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.core.BaseServiceImpl;
import com.seek.dao.CustomerCardDao;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TBizFlow;
import com.seek.model.entity.TCustomerCard;
import com.seek.service.BizFlowService;
import com.seek.service.CustomerCardService;
import com.seek.service.CustomerService;
import com.seek.util.CommonUtil;
import com.seek.util.MapUtil;


@Repository("customerCardService")
public class CustomerCardServiceImpl extends BaseServiceImpl<TCustomerCard> implements CustomerCardService {
	 private static Logger logger = LoggerFactory.getLogger(CustomerCardServiceImpl.class); 
	private  BizFlowService  bizFlowService =  (BizFlowService)SpringContextHolder.getBean("bizFlowService");
	
	private  CustomerService  customerService =  (CustomerService)SpringContextHolder.getBean("customerService");
	
	@Autowired
	public void setDao(CustomerCardDao customerCardDao) {
		super.setDao(customerCardDao);
	}
	public CustomerCardDao getDao() {
		return (CustomerCardDao) super.getDao();
	}
	public void saveBatch(List<TCustomerCard> datas) throws Exception {
		if (datas == null || datas.size() < 1)
			return;
		for (TCustomerCard en : datas){
			this.getDao().insert(en);
		}
		
	}
	
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void addBankBind(Map<String, Object> map) throws Exception{
		ResultInfo result = new ResultInfo();
		String sql= "";
		TCustomerCard custometCard = (TCustomerCard) map.get("tcustomerCard");
		String type = map.get("type")+"";
		if(type.equals("update")){
		sql = "update t_customer_card set history=? where  customer_id = ? and company_id = ?   and history=0";
			this.getDao().executeUpdateSql(sql,new Object[]{1,custometCard.getCustomerId(),custometCard.getCompanyId()});
		}
		//修改用户之前绑定的银行卡信息为历史数据成功之后进行添加银行卡绑定信息
		this.getDao().saveOrUpdate(custometCard);
	}
	
	
	
	@Transactional
	public void updateBankBind(Map<String, Object> map) throws Exception {
		String sql = "";
		String orgCode = map.get("orgCode")+"";
		if(orgCode.equals("YOUDUN")){
			map.put("cardStatus",RetCodeEnum.getRetCodeEnumByValue("udcard", map.get("status")+"").getDesc());
			map.put("userStatus", RetCodeEnum.getRetCodeEnumByValue("uduser", map.get("status")+"").getDesc());
		}else{
			map.put("cardStatus",RetCodeEnum.getRetCodeEnumByValue("nycard", map.get("status")+"").getDesc());
			map.put("userStatus", RetCodeEnum.getRetCodeEnumByValue("nyuser", map.get("status")+"").getDesc());
		}
		
		String udtype = map.containsKey("udtype")==true?map.get("udtype")+"":null;
		String nytype = map.containsKey("nytype")==true?map.get("nytype")+"":null;
		
		if(StringUtils.isNotBlank(udtype)){
			sql = "update t_biz_flow set modify_time=?,status=?,org_biz_no=?,org_code =? where biz_no = ? and deleted=0";
			logger.info(JSON.toJSONString(map)+"=====================JSON.toJSONString(map)===========orgCode:"+orgCode);
			bizFlowService.executeUpdate(sql,new Object[]{new Date(),udtype,map.get("orderNo"),orgCode,map.get("seq")});
		}
		if(StringUtils.isNotBlank(nytype)&&!"1".equals(map.get("history")+"")){
			//有盾调用失败之后，调用的楠云，所以需要从新生成一笔tbizflow
			TBizFlow bizFlow = new TBizFlow();
			bizFlow.setCompanyId(CommonUtil.getLongValue(map.get("companyId")));
			bizFlow.setCustomerId(CommonUtil.getLongValue(map.get("custId")));
			bizFlow.setBizNo(map.get("seq").toString());
			bizFlow.setBizType("银行4要素认证");
			bizFlow.setOrgCode("NANYUN");
			bizFlow.setDeleted(0);
			bizFlow.setOrgBizNo(map.get("orderNo").toString());
			bizFlow.setStatus(nytype);
			bizFlow.setCreateTime(new Date());
			bizFlow.setModifyTime(new Date());
			bizFlowService.save(bizFlow);
		}
		//修改银行卡绑定信息
		sql = "update t_customer_card set audit_status=? , audit_remark=? , audit_time=now(),bank_name=? where company_id=? and customer_id=? and history=?";
		this.getDao().executeUpdateSql(sql,new Object[]{map.get("cardStatus"),map.get("message"),map.containsKey("orgName")?map.get("orgName"):"",map.get("companyId"),map.get("custId"),map.containsKey("history")?map.get("history"):0});
		//修改客户表信息
		sql = "update t_customer set card_bind_status=? where id = ?";
		customerService.executeUpdate(sql,new Object[]{map.get("userStatus")+"",CommonUtil.getLongValue(map.get("custId"))});
		
		String custToken = CacheUtil.getRedisData("COUSTOMER_TOKEN_" + map.get("custId"));  
		//不知道失败是否刷新缓存
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("bankName", map.get("bankName"));
		m.put("cardNumber", map.get("cardNumber"));
		CacheUtil.refreshCustRedis(custToken, m);
	}
	

}